package com.glamour.hlcity.componenet.task.factory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.CollectionUtils;
import com.glamour.hlcity.common.enums.ErrorCodeEnum;
import com.glamour.hlcity.component.framework.registry.ServiceRegistry;
import com.glamour.hlcity.component.task.api.CreateExecuteUnit;
import com.glamour.hlcity.component.task.api.ExecuteUnit;
import com.glamour.hlcity.component.task.common.BeanUtil;
import com.glamour.hlcity.component.task.common.TaskException;
import com.glamour.hlcity.component.task.impl.RunnableUnit;
import com.glamour.hlcity.component.task.model.Command;

public class RunnableFactory {
	private final static Log LOG = LogFactory.getLog(RunnableFactory.class);
	
	private TaskFactory taskFactory;
	
	public final static String DAEMON_THREAD_POOL="DAEMON_THREAD_POOL";
	
	
	public void setTaskFactory(TaskFactory taskFactory) {
		this.taskFactory = taskFactory;
	}

	/**
	 * 创建一个特定的执行单元
	 * @param type
	 * @param seqno
	 * @return
	 */
	public Runnable create(String type, String seqno) {
		LOG.info("创建一个线程执行单元,类型:".concat(type).concat(",业务编号").concat(seqno));
		ExecuteUnit execute=taskFactory.executeUnit(type);
		return new RunnableUnit(execute, type, seqno);
	}
	
	/**
	 * 获取守护线程中所有待执行的单元
	 * @param total
	 * @return
	 */
	public List<Runnable> queryRunnableUnit(Integer total){
		List<CreateExecuteUnit> executeList=queryExecuteUnitList();//filter(queryExecuteUnitList());
		List<Runnable> runnableList=new ArrayList<Runnable>();
		
		for(CreateExecuteUnit execute:executeList){
			runnableList.addAll(runnableList(execute.createExecuteUnit()));
		}
		if(runnableList.size()>total){
			LOG.error("守护线程执行能力有限不能超过".concat(total.toString().concat("个执行命令")));
			throw new TaskException(ErrorCodeEnum.M010002,"守护线程执行能力有限不能超过".concat(total.toString().concat("个执行命令")));
		}
		return runnableList;
	}

	/**
	 * 命令转换
	 * @param commandList
	 * @return
	 */
	private List<Runnable> runnableList(List<Command> commandList){
		List<Runnable> runnableList=new ArrayList<Runnable>();
		for(Command command:commandList){
			runnableList.add(create(command.getType(), command.getSeqno()));
		}
		return runnableList;
		
	}
	
	/**
	 * 获取所有载入到守护线程中的执行器
	 * @return
	 */
	private List<CreateExecuteUnit> queryExecuteUnitList(){
		List<CreateExecuteUnit> collection=taskFactory.createExecuteUnit();
		return collection;
	}

	private List<CreateExecuteUnit> filter(List<CreateExecuteUnit> executeList){
		 List<CreateExecuteUnit> list=new ArrayList<CreateExecuteUnit>();
		 for(CreateExecuteUnit execute:executeList){
			 CreateExecuteUnit temp=BeanUtil.getBeanWithExecuteTarget(execute, DAEMON_THREAD_POOL);
			 if(temp==null){
				 continue;
			 }
			 list.add(temp);
		 }
		return list;
	}
}
